package com.casems.commons.util;

import com.casems.commons.execption.ParamExecption;
import org.apache.commons.collections4.CollectionUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Set;
import java.util.stream.Collectors;

public class ValidatorUtil {
    private static final Validator validator;

    static {
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        validator = factory.getValidator();
    }

    public static void validator(Object object) {
        Set<ConstraintViolation<Object>> violations = validator.validate(object);
        if (CollectionUtils.isNotEmpty(violations)) {
            String message = violations.stream().map(x -> x.getPropertyPath().toString() + x.getMessage())
                    .collect(Collectors.joining(";"));
            throw new ParamExecption(message);
        }
    }
}
